package com.ahm.service;

import com.ahm.base.BaseService;
import com.ahm.bean.CusDevPlan;
import com.ahm.bean.SaleChance;
import com.ahm.mapper.CusDevPlanMapper;
import com.ahm.mapper.SaleChanceMapper;
import com.ahm.query.CusDevPlanQuery;
import com.ahm.utils.AssertUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/*功能描述
 * @author ahm
 */
@Service
public class CusDevPlanService extends BaseService<CusDevPlan,Integer> {

    @Resource
    private CusDevPlanMapper cusDevPlanMapper;
    @Resource
    private SaleChanceMapper saleChanceMapper;


    public Map<String,Object> queryCusDevPlanByParams(CusDevPlanQuery cusDevPlanQuery){
        Map<String,Object> map = new HashMap<>();
        PageHelper.startPage(cusDevPlanQuery.getPage(),cusDevPlanQuery.getLimit());
        PageInfo<CusDevPlan> pageInfo = new PageInfo<>(cusDevPlanMapper.selectByParams(cusDevPlanQuery));
        map.put("code",0);
        map.put("msg","");
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        return map;

    }

    /**
     * 添加计划项
     * 1. 参数校验
     * 营销机会ID 非空 记录必须存在
     * 计划项内容 非空
     * 计划项时间 非空
     * 2. 设置参数默认值
     * is_valid
     * crateDate
     * updateDate
     CusDevPlanController.java
     4.3.3. 计划项更新
     4.3.3.1. 实现思路
     * 3. 执行添加，判断结果
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveCusDevPlan(CusDevPlan cusDevPlan) {
// 1. 参数校验
        checkParams(cusDevPlan.getSaleChanceId(),
                cusDevPlan.getPlanItem(), cusDevPlan.getPlanDate());
// 2. 设置参数默认值
        cusDevPlan.setIsValid(1);
        cusDevPlan.setCreateDate(new Date());
        cusDevPlan.setUpdateDate(new Date());
// 3. 执行添加，判断结果
        AssertUtil.isTrue(insertSelective(cusDevPlan) < 1, "计划项记录添加失败！");
    }


    /**
     * 验证参数
     * @param saleChanceId
     * @param planItem
     * @param planDate
     */
    private void checkParams(Integer saleChanceId, String planItem, Date planDate) {
        AssertUtil.isTrue(null == saleChanceId ||
                saleChanceMapper.selectByPrimaryKey(saleChanceId) == null, "请设置营销机会ID！");
        AssertUtil.isTrue(StringUtils.isBlank(planItem), "请输入计划项内容！");
        AssertUtil.isTrue(null == planDate, "请指定计划项日期！");
    }

}
